const Promise = require('bluebird');
const apis = {};

/**
 * 基础设置Api
 */
const settingsV1 = require('./v1/settings');
Object.assign(apis, {
    '/v1/settings/schedule': {
        handler: settingsV1.schedule
    },
    '/v1/settings/tasks': {
        handler: settingsV1.tasks
    }
});

/**
 * 请求转发，权限控制，数据处理
 */
module.exports = function (storage, config) {
    return function (req, res) {
        let {path, body, query} = req;

        let api = apis[path];
        if (api) {
            let {handler, permission} = api;
            if (permission === 'key') {
                let key = query.key;
                if (!key || key != config.webservice_key) {
                    return res.status('403').json({success: false, code: 403, message: '没有访问权限，密钥验证失败'});
                }
            }
            return Promise.resolve().then(function () {
                return handler({
                    req: req, res: res, body: body, query: query
                }, storage);
            }).then(function (response) {
                res.json(response);
            }, function (err) {
                if (err) {
                    console.error('\n', err.stack || err.message)
                }
                res.json({success: false, code: 500, message: err && err.message || '请求异常'});
            });
        } else {
            return res.json({success: false, code: 404, message: '无效API'});
        }
    }
}